By atharvaparab9160
There is a restaurant with a single chef. You are given an array customers, where customers[i] = [arrival i, time i]:
Return the average waiting time of all customers. Solutions within 10^-5 from the actual answer are considered accepted.
The solution involves a single pass through the list of customers O(n), where n is the number of customers.
The space complexity of the solution is dominated by the input storage, which is O(N), where n is the number of customers. Apart from the input storage, the solution uses a constant amount of extra space O(1) for variables like wait and cur.
def averageWaitingTime(Customers):
wait = 0 # Initialize total waiting time
cur = Customers[0][0] # Initialize current time to the arrival time of the first customer
for i in Customers:
arrive = i[0] # Arrival time of the current customer
time_for_cooking = i[1] # Time required for cooking for the current customer
if arrive < cur:
wait += (cur - arrive + time_for_cooking) # Customer waits until the current time + their service time
cur += time_for_cooking # Update current time to when this customer finishes
else:
wait += time_for_cooking # Customer arrives after or exactly at current time, start service immediately
cur = arrive + time_for_cooking # Update current time to when this customer finishes
return wait / len(Customers) # Calculate and return the average waiting time
customers = [[5,2],[5,4],[10,3],[20,1]]
print(f" Waiting Time : {averageWaitingTime(Customers)}")
"""
Intuition :
-The algorithm simulates the process of serving customers starting from the first customer's arrival time.
-It tracks the current time (cur) to manage when each customer can start being served based on their arrival times and the service times of previous customers.
-By iterating through each customer and updating cur accordingly, it accurately computes the waiting times and subsequently the average waiting time for all customers.
-This approach ensures that each customer's waiting time is correctly calculated based on when they arrive relative to when they can start being served, and it efficiently computes the required average waiting time at the end.
"""